package com.example.okhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {
private static final String TAG="tag";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intiview();
    }
    private void intiview(){
        Button button=findViewById(R.id.btn_http);
        Button button1=findViewById(R.id.btn_httppost);
        //创建OkHttpClient
        OkHttpClient client=new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                       Request request=chain.request();
                       //首次访问后后台返回的认证，防止被抓包后篡改请求
                        request.newBuilder().addHeader("authorization","xxx");
                        //登录后服务端返回的回话ID，用于长登录的维持回话作用
                        request.newBuilder().addHeader("session_id/token","xxx");
                        long startTime=System.currentTimeMillis();
                        Response response=chain.proceed(chain.request());
                        long endTime=System.currentTimeMillis();
                        long duration=endTime-startTime;
                        MediaType mediaType=response.body().contentType();
                        String content=response.body().string();
                        Log.d(TAG, "请求地址: "+"  intercept  "+request.toString());
                        Log.d(TAG, "返回数据: "+"  intercept  "+content);
                        Log.d(TAG, "数据格式: "+"  intercept  "+mediaType);
                        Log.d(TAG, "时间: "+"  请求耗时  "+duration+"毫秒");
                        return  response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
                    }
                }).build();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //创建请求体
                Request getreq=new Request.Builder().url(
                        "http://apis.juhe.cn/simpleWeather/cityList?key=f316e87349acc334385260de4a67b6bc")
                        .build();

                //发送请求
                //client.newCall(getreq).execute()方法为同步方法，需要添加子线程发送
               // client.newCall(getreq).enqueue()方法为异步方法，通过监听回调方法接收
                client.newCall(getreq).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String jsonstr=response.body().string();
                        Log.d(TAG, "城市: "+jsonstr);
                    }
                });

            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //构建请求参数
                RequestBody body=new FormBody.Builder().add("key","f316e87349acc334385260de4a67b6bc").build();
                Request postreq=new Request.Builder().url(
                        "http://apis.juhe.cn/simpleWeather/cityList").post(body).build();
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            Response response= client.newCall(postreq).execute();
//                            String jsonst=response.body().string();
//                            Log.d(TAG, "查询城市结果: "+jsonst);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

            }
        });
    }
}